package com.itheima.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.itheima.model.mongo.RecommendUser;
import com.itheima.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    /*今日佳人*/
    @Override
    public RecommendUser queryWithMaxScore(Long toUserId) {
        Query query = Query.query(Criteria.where("toUserId").is(toUserId)).limit(1).with(Sort.by(Sort.Order.desc("score")));
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);
        return user;
    }
    /*不分也查询*/
    @Override
    public Map<Long, RecommendUser> pageWithScore(Long toUserId) {
        Query query = Query.query(Criteria.where("toUserId").is(toUserId)).with(Sort.by(Sort.Order.desc("score")));
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        Map<Long, RecommendUser> userMap = CollUtil.fieldValueMap(recommendUserList, "userId");
        return userMap;
    }
    //查看佳人详情
    @Override
    public RecommendUser quryByHuanxin(Long userId, Long toUserId) {
        Query query = Query.query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);
        //构造假的数据
        if(user==null){
             user = new RecommendUser();
            user.setUserId(userId);
            user.setToUserId(toUserId);
            user.setScore(95d);
        }
        return user;
    }

    @Override
    public List<RecommendUser> quryCardList(Long userId, int counts) {
        //排除喜欢/不喜欢（已经看过的）数据
        List<UserLike> userLikes = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), UserLike.class);
        List<Long> userIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        userIds.add(userId);//查询推荐的人的时候把自己排除了
        Criteria criteria = Criteria.where("toUserId").is(userId).and("userId").nin(userIds);//nin不在范围内
        List<RecommendUser> res = getRandomRecommend(counts, criteria);
        if (CollUtil.isEmpty(res)){//发现没有推荐给自己的数据
            res = getRandomRecommend(counts, Criteria.where("userId").nin(userIds));//就设置假数据（不推荐给自己的也可以查）但是不重复
            if (CollUtil.isEmpty(res)){//发现没有推荐和推荐的数据都是空
                res=new ArrayList<>();
            }
        }
        return res;


    }
    /*推荐好友分页查询*/
   /* @Override
    public List<RecommendUser> pageWithScore(Long toUserId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("toUserId").is(toUserId)).with(PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("score"))));
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        return recommendUserList;
    }*/
   public List<RecommendUser> getRandomRecommend(int counts,Criteria criteria){
       //随机获取推荐数据
       TypedAggregation<RecommendUser> aggregation = TypedAggregation.newAggregation(RecommendUser.class,
               Aggregation.match(criteria),//指定查询条件
               Aggregation.sample(counts)//条数
       );
       AggregationResults<RecommendUser> aggregate = mongoTemplate.aggregate(aggregation, RecommendUser.class);//统计查询
       List<RecommendUser> res = aggregate.getMappedResults();
       return res;
   }



}
